package edu.neu.chenhan.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import edu.neu.chenhan.R;
import edu.neu.chenhan.listener.OnItemClickListener;
import edu.neu.chenhan.model.CooperationCategory;

import java.util.List;

public class CooperationCategoryAdapter extends RecyclerView.Adapter<CooperationCategoryAdapter.CooperationViewHolder> {
    private List<CooperationCategory> categoryList;
    private OnItemClickListener listener;
    private Context context;

    public CooperationCategoryAdapter(Context context, List<CooperationCategory> categoryList, OnItemClickListener listener) {
        this.context = context;
        this.categoryList = categoryList;
        this.listener = listener;
    }

    @NonNull
    @Override
    public CooperationViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_cooperation_category, parent, false);
        return new CooperationViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull CooperationViewHolder holder, int position) {
        CooperationCategory category = categoryList.get(position);
        holder.tvCategoryName.setText(category.getName());
        holder.tvCategoryDescription.setText(category.getDescription());

        // 动态加载图标资源
        int resId = context.getResources().getIdentifier(category.getIconRes(), "drawable", context.getPackageName());
        if (resId != 0) {
            holder.ivCategoryIcon.setImageResource(resId);
        } else {
            holder.ivCategoryIcon.setImageResource(R.drawable.ic_search);
        }

        // 设置点击事件
        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onItemClick(position);
            }
        });
    }

    @Override
    public int getItemCount() {
        return categoryList.size();
    }

    // 获取指定位置的分类
    public CooperationCategory getItem(int position) {
        return categoryList.get(position);
    }

    public static class CooperationViewHolder extends RecyclerView.ViewHolder {
        ImageView ivCategoryIcon;
        TextView tvCategoryName, tvCategoryDescription;

        public CooperationViewHolder(@NonNull View itemView) {
            super(itemView);
            ivCategoryIcon = itemView.findViewById(R.id.iv_category_icon);
            tvCategoryName = itemView.findViewById(R.id.tv_category_name);
            tvCategoryDescription = itemView.findViewById(R.id.tv_category_description);
        }
    }
}